import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Modal, notification } from 'ant-design-vue'
import { encrypt } from './ASE'
/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
let apiBaseUrl = `${window.location.protocol}//${window.location.host}` + '/law-boot/web'

// 创建 axios 实例
const service = axios.create({
  //baseURL: '/jeecg-boot',
  baseURL: apiBaseUrl, // api base_url
  timeout: 20000, // 请求超时时间
})
let Forbidden = false // 标记接口权限
let isRefreshing = false // 标记是否正在刷新 token

let requests = [] // 存储待重发请求的数组

// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (token) {
      config.headers['X-WEB-TOKEN'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    // let rs = {}
    // if (config.data) {
    //   rs = encrypt(JSON.stringify(config.data))
    //   console.log('加密前', rs)
    //   config.data = {
    //     keys: rs,
    //   }
    // } else if (config.params) {
    //   rs = encrypt(config.params)
    //   config.params = { param: rs.encoded }
    // }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (response.data.code && response.data.code !== 200) {
      notification.error({
        message: '系统提示',
        description: response.data.message,
        duration: 4,
      })
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  },
  async (error) => {
    console.log('响应异常', error.response)
    if (error.response) {
      let data = error.response.data
      const token = Vue.ls.get(ACCESS_TOKEN)

      switch (error.response.status) {
        case 403:
          if (Forbidden == false) {
            Forbidden = true
            notification.error({
              message: '系统提示',
              description: '没有权限访问',
              duration: 4,
            })
            setTimeout(() => {
              Forbidden = false
            }, 3000)
          }
          break
        case 502:
        case 500:
          console.log('------error.response------', error.response)
          notification.error({
            message: '系统提示',
            description: '服务器内部异常',
            duration: 4,
          })
          break
        case 401:
          let { data, config } = error.response

          // 如果正在刷新
          if (isRefreshing) {
            return new Promise((resolve) => {
              requests.push({
                config,
                resolve,
              })
            })
          }

          // 判断如果这个请求不是刷新 token 的
          if (!config.url.includes('/refresh_token')) {
            try {
              isRefreshing = true
              await store.dispatch('getRefreshToken')
              isRefreshing = false
              console.log('刷新 Token 成功！！！！')
              // window.location.reload()
              // 无感刷新部分页面不能正常加载
              requests.forEach(({ config, resolve }) => {
                resolve(service(config))
              })
              // console.log(requests, '请求的列表')
              requests = [] // 重新请求完清空
              return service(config)
            } catch (error) {
              console.log(error, 'Error getting refresh token')
              if (error.code !== 200) {
                Modal.error({
                  title: '登录已过期',
                  content: '很抱歉，登录已过期，请重新登录',
                  okText: '重新登录',
                  mask: false,
                  onOk: () => {
                    store.dispatch('Logout').then(() => {
                      Vue.ls.remove(ACCESS_TOKEN)
                      window.location.reload()
                    })
                  },
                })
              }
            } finally {
              isRefreshing = false
            }
          } else {
            return error.response
          }
          break
        case 404:
          notification.error({
            message: '系统提示',
            description: '很抱歉，资源未找到!',
            duration: 4,
          })
          break
        case 504:
          notification.error({
            message: '系统提示',
            description: '网络超时',
          })
          break
        default:
          notification.error({
            message: '系统提示',
            description: data.message,
            duration: 4,
          })
          break
      }
    } else if (error.message) {
      if (error.message.includes('timeout')) {
        notification.error({
          message: '系统提示',
          description: '网络超时',
        })
      } else {
        notification.error({
          message: '系统提示',
          description: error.message,
        })
      }
    }
    return Promise.reject(error)
  }
)

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  },
}

export { installer as VueAxios, service as axios }
